package com.aw.baselib.util

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.Log
import android.view.Window
import android.view.WindowManager
import android.widget.Toast
import java.io.File
import java.math.BigDecimal
import java.util.UUID

/**
 * 应用辅助工具栏
 * 如：设备号，应用版本号以及版本名字
 * Created by hzw
 */
object AwAppUtils {
    const val APP_FOLDER = "ShareFun"

    /**
     * 获取唯一设备id
     *
     * @param context
     * @return
     */
    @SuppressLint("MissingPermission")
    fun getUniqueID(context: Context?): String? {
        if (context == null) {
            return null
        }
        val appContent = context.applicationContext
        val tm =
            appContent.applicationContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val tmDevice: String
        val tmSerial: String
        val androidId: String
        tmDevice = "" + tm.deviceId
        tmSerial = "" + tm.simSerialNumber
        androidId = "" + Settings.Secure.getString(
            appContent.contentResolver,
            Settings.Secure.ANDROID_ID
        )
        val deviceUuid = UUID(
            androidId.hashCode().toLong(),
            tmDevice.hashCode().toLong() shl 32 or tmSerial.hashCode().toLong()
        )
        return deviceUuid.toString()
    }

    /**
     * 获取version_name或者version_code
     *
     * @param context
     * @param version_type {}
     * @return
     */
    fun getAppVersionInfo(context: Context?, version_type: TYPE_VERSION): String? {
        if (context == null) {
            return null
        }
        var versionCode: String? = null
        var versionName: String? = null
        val appContent = context.applicationContext
        val pm = appContent.packageManager
        var pi: PackageInfo? = null
        try {
            pi = pm.getPackageInfo(appContent.packageName, 0)
            versionName = pi.versionName
            versionCode = pi.versionCode.toString() + ""
        } catch (e: PackageManager.NameNotFoundException) {
            versionName = null
            versionCode = null
        }
        return if (version_type == TYPE_VERSION.TYPE_VERSION_CODE) {
            versionCode
        } else {
            versionName
        }
    }

    /**
     * 格式化文件大小单位
     *
     * @param size 单位 KB
     * @return
     */
    fun getFormatSize(size: Double): String {
        val kiloByte = size / 1024
        val result2 = BigDecimal(java.lang.Double.toString(kiloByte))
        return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
            .toPlainString() + "MB"
    }

    fun isTopActivity(context: Context, activityName: String?): Boolean {
        val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningTaskInfos = manager.getRunningTasks(1)
        return if (runningTaskInfos != null) {
            runningTaskInfos[0].topActivity.toString().contains(activityName!!)
        } else {
            false
        }
    }

    /**
     * 检查是否有新版本
     *
     * @param localVersionName
     * @param serviceVersionName
     * @return
     */
    fun hasNewVersion(localVersionName: String, serviceVersionName: String): Boolean {
        var localVersionName = localVersionName
        var serviceVersionName = serviceVersionName
        localVersionName = localVersionName.replace(".", "_")
        serviceVersionName = serviceVersionName.replace(".", "_")
        var hasNew = false
        if (TextUtils.isEmpty(localVersionName) || TextUtils.isEmpty(serviceVersionName)) {
            hasNew = false
        } else {
            val localArrays = localVersionName.split("_".toRegex()).dropLastWhile { it.isEmpty() }
                .toTypedArray()
            val servicesArrays =
                serviceVersionName.split("_".toRegex()).dropLastWhile { it.isEmpty() }
                    .toTypedArray()
            try {
                if (localArrays != null && localArrays.size > 0 && servicesArrays != null && servicesArrays.size > 0) {
                    val localLen = localArrays.size
                    val servicesLen = servicesArrays.size
                    for (i in 0 until servicesLen) {
                        var li = 0
                        if (localLen > i) {
                            li = localArrays[i].toInt()
                        }
                        val si = servicesArrays[i].toInt()
                        if (si > li) {
                            hasNew = true
                            break
                        } else if (si < li) {
                            hasNew = false
                            break
                        } else {
                            continue
                        }
                    }
                } else {
                    hasNew = false
                }
            } catch (e: NumberFormatException) {
            }
        }
        return hasNew
    }

    /**
     * 获取已经安装的app_name
     *
     * @return
     */
    fun getInstalledApp(context: Context, app_Name: String): Boolean {
        val pm = context.applicationContext.packageManager
        val pinfo = pm.getInstalledPackages(0)
        val listAppName: MutableList<String> = ArrayList()
        if (pinfo != null) {
            for (i in pinfo.indices) {
                val info = pinfo[i]
                val appName = info.applicationInfo!!.loadLabel(pm).toString()
                listAppName.add(appName)
            }
        }
        return listAppName.contains(app_Name)
    }

    /**
     * 是否是横屏
     *
     * @param context
     * @return
     */
    fun isLandscape(context: Context): Boolean {
        val flag: Boolean
        flag = if (context.resources.configuration.orientation == 2) {
            true
        } else {
            false
        }
        return flag
    }

    /**
     * 是否是竖屏
     *
     * @param context
     * @return
     */
    fun isPortrait(context: Context): Boolean {
        var flag = true
        if (context.resources.configuration.orientation != 1) {
            flag = false
        }
        return flag
    }

    /**
     * 安装应用
     *
     * @param context
     * @param file
     */
    fun installAPK(context: Context, file: File?) {
        if (file == null || !file.exists()) {
            return
        }
        val intent = Intent()
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.action = Intent.ACTION_VIEW
        intent.setDataAndType(
            Uri.fromFile(file),
            "application/vnd.android.package-archive"
        )
        context.startActivity(intent)
    }

    fun getInstallApkIntent(file: File?): Intent {
        val intent = Intent()
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.action = Intent.ACTION_VIEW
        intent.setDataAndType(
            Uri.fromFile(file),
            "application/vnd.android.package-archive"
        )
        return intent
    }

    /**
     * 获取应用程序名称
     */
    fun getAppName(context: Context): String? {
        try {
            val packageManager = context.packageManager
            val packageInfo = packageManager.getPackageInfo(
                context.packageName, 0
            )
            val labelRes = packageInfo.applicationInfo!!.labelRes
            return context.resources.getString(labelRes)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 修改Activity的状态栏颜色
     *
     * @param activity   Activity
     * @param colorResId Color
     */
    fun setWindowStatusBarColor(activity: Activity, colorResId: Int) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val window = activity.window
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.statusBarColor = activity.resources.getColor(colorResId)
                //底部导航栏
                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    fun FlymeSetStatusBarLightMode(window: Window?, dark: Boolean): Boolean {
        var result = false
        if (window != null) {
            try {
                val lp = window.attributes
                val darkFlag = WindowManager.LayoutParams::class.java
                    .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON")
                val meizuFlags = WindowManager.LayoutParams::class.java
                    .getDeclaredField("meizuFlags")
                darkFlag.isAccessible = true
                meizuFlags.isAccessible = true
                val bit = darkFlag.getInt(null)
                var value = meizuFlags.getInt(lp)
                value = if (dark) {
                    value or bit
                } else {
                    value and bit.inv()
                }
                meizuFlags.setInt(lp, value)
                window.attributes = lp
                result = true
            } catch (e: Exception) {
                Log.e("APPUtils", "FlymeSetStatusBarLightMode: ", e)
            }
        }
        return result
    }

    /**
     * 设置状态栏字体图标为深色，需要MIUIV6以上
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    fun MIUISetStatusBarLightMode(window: Window?, dark: Boolean): Boolean {
        var result = false
        if (window != null) {
            val clazz: Class<*> = window.javaClass
            try {
                var darkModeFlag = 0
                val layoutParams = Class.forName("android.view.MiuiWindowManager\$LayoutParams")
                val field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
                darkModeFlag = field.getInt(layoutParams)
                val extraFlagField = clazz.getMethod(
                    "setExtraFlags",
                    Int::class.javaPrimitiveType,
                    Int::class.javaPrimitiveType
                )
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag) //状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag) //清除黑色字体
                }
                result = true
            } catch (e: Exception) {
                Log.e("APPUtils", "MIUISetStatusBarLightMode: ", e)
            }
        }
        return  /*result*/false
    }

    /**
     * 方法描述：判断某一应用是否正在运行
     * @param context     上下文
     * @param packageName 应用的包名
     * @return true 表示正在运行，false 表示没有运行
     */
    fun isAppRunning(context: Context, packageName: String): Boolean {
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val list = am.getRunningTasks(100)
        if (list.size <= 0) {
            return false
        }
        for (info in list) {
            if (info.baseActivity!!.packageName == packageName) {
                return true
            }
        }
        return false
    }

    //获取已安装应用的 uid，-1 表示未安装此应用或程序异常
    fun getPackageUid(context: Context, packageName: String?): Int {
        try {
            val applicationInfo = context.packageManager.getApplicationInfo(
                packageName!!, 0
            )
            if (applicationInfo != null) {
                AwLog.d(applicationInfo.uid.toString() + "")
                return applicationInfo.uid
            }
        } catch (e: Exception) {
            return -1
        }
        return -1
    }

    /**
     * 判断某一 uid 的程序是否有正在运行的进程，即是否存活
     * @param context     上下文
     * @param uid 已安装应用的 uid
     * @return true 表示正在运行，false 表示没有运行
     */
    fun isProcessRunning(context: Context, uid: Int): Boolean {
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningServiceInfos = am.getRunningServices(200)
        if (runningServiceInfos.size > 0) {
            for (appProcess in runningServiceInfos) {
                if (uid == appProcess.uid) {
                    return true
                }
            }
        }
        return false
    }

    /**
     * [获取应用程序版本名称信息]
     * @param context
     * @return 当前应用的版本名称
     */
    fun getPackageName(context: Context): String? {
        try {
            val packageManager = context.packageManager
            val packageInfo = packageManager.getPackageInfo(
                context.packageName, 0
            )
            return packageInfo.packageName
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun checkAppRun(context: Context, packageName: String) {
        val uid = getPackageUid(context, packageName)
        if (uid > 0) {
            val rstA = isAppRunning(context, packageName)
            val rstB = isProcessRunning(context, uid)
            if (rstA || rstB) {
                //指定包名的程序正在运行中
            } else {
                //指定包名的程序未在运行中
            }
        } else {
            //应用未安装
        }
    }

    fun toOtherApp(context: Context, packname: String) {
        val packageManager = context.packageManager
        if (getPackageUid(context, packname) != -1) {
            val intent = packageManager.getLaunchIntentForPackage(packname)
            context.startActivity(intent)
        } else {
            Toast.makeText(context, "没有安装$packname", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 类型，获取版本信息
     */
    enum class TYPE_VERSION {
        /**
         * 版本名称
         */
        TYPE_VERSION_NAME,

        /**
         * 版本号
         */
        TYPE_VERSION_CODE
    }
}